import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'dart:math';

/**
 * @Description: 自定义 进度条
 *    参考 https://www.daimajiaoliu.com/daima/6cf84e19396e806
 * @Author: 下雨了
 * @CreateDate: 2022-06-13 9:21
 * @UpdateUser: 更新者
 * @UpdateDate:  2022-06-13 9:21
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */

///
class CustomerProgress extends CustomPainter {
  final Color backgroundColor; //背景色
  final Color startProgressColor; //前景 开始色 渐变
  final Color endProgressColor; //前景  结束色 渐变
  final double startPointAngle; // Canvas绘制开始位置
  final double endPointAngle; //结束位置
  final bool centerClose; //圆弧是否闭合
  final double radius; //半径
  final double lineWidth; //所绘制线条的宽度
  final double value; //进度条的value
  final TextStyle? style; //进度条文本风格（非必须）
  final String? completeText; //进度条文本（非必须）

  CustomerProgress({
    Key? key,
    this.backgroundColor = Colors.black12,
    this.startProgressColor = Colors.red,
    this.endProgressColor = Colors.red,
    this.startPointAngle = 0.0,
    this.endPointAngle = 1.0,
    this.centerClose = false,
    this.radius = 180,
    this.lineWidth = 10,
    required this.value,
    this.style,
    this.completeText,
  });

  @override
  void paint(Canvas canvas, Size size) {
    Rect rect = Rect.fromCircle(
        center: Offset(size.width / 2, size.height / 2), radius: radius);
    double startAngle = degToRad(startPointAngle) as double; // 为起始弧度
    double sweepAngle = degToRad(endPointAngle) as double; //  需要绘制的圆弧长度

    // 最底层白色背景
    Paint paint = Paint() //初始化画笔
      ..color = Colors.white
      ..style = PaintingStyle.stroke //画笔样式
      ..strokeCap = StrokeCap.butt //画笔笔头类型
      ..strokeWidth = lineWidth + 17; //画笔的宽度
    canvas.drawArc(rect, startAngle, sweepAngle, centerClose, paint);


    // 渐变底色
    paint
      ..color = backgroundColor //背景颜色
      ..style = PaintingStyle.stroke //画笔样式
      ..strokeCap = StrokeCap.butt //画笔笔头类型
      ..strokeWidth = lineWidth; //画笔的宽度
    //通过Canvas绘制一条弧线
    canvas.drawArc(rect, startAngle, sweepAngle, centerClose, paint);
    //背景弧线绘制完成

    // 前景 前景色
    final Gradient gradient = new LinearGradient(
      colors: [
        startProgressColor,
        endProgressColor,
      ],
    );
    paint
      ..strokeWidth = lineWidth //画笔宽度，在这里我们设置得比背景的宽度稍宽些
      ..style = PaintingStyle.stroke
      ..strokeCap = StrokeCap.butt
      ..shader = gradient.createShader(rect);

    canvas.drawArc(rect, startAngle, sweepAngle * value, centerClose, paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return true;
  }
}

/// 弧度与角度的弧线转换
/// 角度  degree
/// 弧度  radian
/// pi = 3.1415926535897932
num degToRad(num deg) {
  return deg * (pi / 180.0);
}

num radToDeg(num rad) {
  return rad * (180.0 / pi);
}
